package red.yancloud.www.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.*;
import android.widget.SeekBar.OnSeekBarChangeListener;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.view.GravityCompat;
import org.greenrobot.eventbus.EventBus;
import red.yancloud.www.R;
import red.yancloud.www.common.Constants;
import red.yancloud.www.common.MessageEvent;
import red.yancloud.www.db.sharedpreference.ReadSettingShardPreference;
import red.yancloud.www.internet.bean.BookMarkEntity;
import red.yancloud.www.manager.DatabaseManager;
import red.yancloud.www.manager.ThemeManager;
import red.yancloud.www.ui.read.EPupReadActivity;
import red.yancloud.www.ui.read.PdfReadActivity;
import red.yancloud.www.util.ToastUtils;

import static red.yancloud.www.util.Utils.getResources;


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/10 16:30
 * E_Mail：yh131412hys@163.com
 * Describe：阅读设置弹出框
 * Change：
 * @Version：V1.0
 */
public class BookReadSettingDialog extends Dialog implements View.OnClickListener,OnSeekBarChangeListener {

	private Context mContext;
	private RelativeLayout bottomMenuLayout;
	private RelativeLayout topMenuLayout;
	private AppCompatTextView dayOrNight;
	private ReadSettingShardPreference readSetting;
	private boolean isMarkPage; // 标记当前页是否添加书签
	private ImageButton downloadBook;
	private ImageButton bookDetail;
	private AppCompatTextView  progressText;

	public BookReadSettingDialog(Context context, int themeResId) {
		super(context, themeResId);
		this.mContext = context;
		init();
	}

	private void init() {
		this.setCancelable(true);
		this.setCanceledOnTouchOutside(true);
	}

	public BookReadSettingDialog(Context context) {
		this(context, R.style.dialog_no_title);
		this.readSetting = ReadSettingShardPreference.Companion.getInstance();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_read_book_setting);

		initView();
		initSetting();
		initAnimationIn();
	}

	private void initSetting() {
		popNightOrDay();

//		Chapter bkChipInfo = pageFactory.getChpInfo();
//		if (bkChipInfo != null) {
////				MarkVo markVo = new MarkVo(pageFactory.getArticleId(),
////						bkChipInfo.getChpId(), pageFactory.getCurPage(),
////						pageFactory.getFirstLineText(), "",
////						mAppContext.getVersionCode(), bkChipInfo.getJsfree(),
////						"", bkChipInfo.getChpName());
//			BookMarkEntity bookMarkEntity = new BookMarkEntity(0);
//			bookMarkEntity.setArticleId(Integer.parseInt(pageFactory.getArticleId()));
//			bookMarkEntity.setChapterId(bkChipInfo.getChapterId());
//			bookMarkEntity.setBegin(pageFactory.getCurPage());
//			bookMarkEntity.setWord(pageFactory.getFirstLineText());
//			bookMarkEntity.setChapterOrder(bkChipInfo.getChapterOrder());
//			bookMarkEntity.setIsFree(bkChipInfo.getJsFree());
//			bookMarkEntity.setChapterName(bkChipInfo.getChapterName());
//			/*
//			 *判断当前页是否已添加为书签
//			 */
//			isMarkPage = DatabaseManager.getInstance().checkMaker(bookMarkEntity);
//		}
//
//		if (isMarkPage) {
//			bookMark.setSelected(true);
//		} else {
//			bookMark.setSelected(false);
//		}
//
//		if(pageFactory.getBKtype() == Constants.BookConfig.LOCAL_BOOKS){
//			if(StringTools.isNum(readSetting.getReadPercent(pageFactory.getArticleId()))){
//				String num = readSetting.getReadPercent(pageFactory.getArticleId()).trim();
//				if(StringTools.isNum(num)){
//					readProSeekBar.setProgress(Integer.parseInt(num.substring(0, num.indexOf("."))));
//				}
//			}
//		}else if(pageFactory.getBKtype() == Constants.BookConfig.SHOP_BOOKS){
//			if(null != pageFactory.getChpInfo()){
//				readProSeekBar.setProgress(readSetting.getShopBookReadPro(pageFactory.getArticleId(), pageFactory.getChpInfo().getChapterId()));
//			}
//		}
	}

	/**
	 * 动画退出
	 */
	private void initAnimationOut() {

		topMenuLayout.clearAnimation();
		Animation animTopOut = AnimationUtils.loadAnimation(mContext, R.anim.top_menu_out);
		topMenuLayout.setAnimation(animTopOut);
		topMenuLayout.startAnimation(animTopOut);

		bottomMenuLayout.clearAnimation();
		Animation animButtomOut = AnimationUtils.loadAnimation(mContext,R.anim.bottom_menu_out);
		bottomMenuLayout.setAnimation(animButtomOut);
		bottomMenuLayout.startAnimation(animButtomOut);

		animButtomOut.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {


			}

			@Override
			public void onAnimationEnd(Animation animation) {
				dismiss();
			}
		});
	}

	private void initAnimationIn() {

		Animation animIn = AnimationUtils.loadAnimation(mContext,
				R.anim.top_menu_in);
		topMenuLayout.setAnimation(animIn);
		Animation animInButtom = AnimationUtils.loadAnimation(mContext,
				R.anim.bottom_menu_in);
		bottomMenuLayout.setAnimation(animInButtom);
	}

	private void initView() {

		Window window = getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		DisplayMetrics dms = mContext.getResources().getDisplayMetrics();
		lp.width = dms.widthPixels;
		lp.height = WindowManager.LayoutParams.MATCH_PARENT;
		window.setAttributes(lp);

		findViewById(R.id.readBookSetting_back_iv).setOnClickListener(this);
		findViewById(R.id.readBookSetting_mark_iv).setOnClickListener(this);
		findViewById(R.id.readBookSetting_share_iv).setOnClickListener(this);
		topMenuLayout = (RelativeLayout) findViewById(R.id.top_menu_layout);

		findViewById(R.id.null_view).setOnClickListener(this);

		bottomMenuLayout = (RelativeLayout) findViewById(R.id.bottom_menu_layout);
		AppCompatTextView titleTv = (AppCompatTextView) findViewById(R.id.readBookSetting_title_tv);
		if (mContext instanceof EPupReadActivity) {

			titleTv.setText(((EPupReadActivity)mContext).getChapterName());

		}else if (mContext instanceof PdfReadActivity){

//			titleTv.setText(((PdfReadActivity)mContext).getIntent().getStringExtra("title"));
//			findViewById(R.id.readBookSetting_lL).setVisibility(View.GONE);
//			findViewById(R.id.readBookSetting_cardView).setVisibility(View.GONE);
		}

		AppCompatSeekBar readProSeekBar = (AppCompatSeekBar) findViewById(R.id.read_progress_seekBar);
		readProSeekBar.setOnSeekBarChangeListener(this);
		readProSeekBar.setMax(100);
		readProSeekBar.setProgress((int) (((EPupReadActivity)mContext).getCurrentProgress()/100.0f*100));
//		progressText = (TextView)findViewById(R.id.read_progress_text);
		findViewById(R.id.readBookSetting_previousChapter_iv).setOnClickListener(this);
		findViewById(R.id.readBookSetting_nextChapter_iv).setOnClickListener(this);
		dayOrNight = (AppCompatTextView) findViewById(R.id.read_dayOrNight);
		dayOrNight.setOnClickListener(this);

		findViewById(R.id.read_catalog).setOnClickListener(this);
		findViewById(R.id.read_setting).setOnClickListener(this);
		findViewById(R.id.read_dayOrNight).setOnClickListener(this);
		findViewById(R.id.read_more).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		Class<?> cls = null;
		switch (v.getId()) {
			case R.id.readBookSetting_back_iv:

				((Activity) mContext).finish();
				break;
			case R.id.readBookSetting_mark_iv:

				EPupReadActivity ePupReadActivity = (EPupReadActivity)mContext;
				AppCompatTextView content = ePupReadActivity.findViewById(R.id.contentTv);

				BookMarkEntity bookMarkEntity = new BookMarkEntity(
						Long.parseLong(ePupReadActivity.bookId),
						Integer.parseInt(ePupReadActivity.getCurrentCid()),
						ePupReadActivity.getScroll_Y(),
						content.getText().subSequence(0,30).toString(),
						System.currentTimeMillis(),
						ePupReadActivity.getChapterName());

				DatabaseManager.Companion.getInstance().addMaker(bookMarkEntity);
				ToastUtils.showToast(R.string.add_bkstore_success);
				break;
			case R.id.readBookSetting_share_iv:

				EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.SHARE,""));
				break;
			case R.id.readBookSetting_previousChapter_iv:

				EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.LOAD_PRE_PAGE,""));
				break;
			case R.id.readBookSetting_nextChapter_iv:

				EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.LOAD_NEXT_PAGE,""));
				break;
			/**
			 * 下载书籍
			 */
//			case R.id.download_book:
//				if(UserSP.getInstance().checkUserBing()){
//					DownLoadBookDialog.getInstance(mContext,pageFactory.getArticleId()).showView();
//				}else{
//					ToastUtils.toastLogin();
//				}
//				break;
			/**
			 * 跳转书籍详情页面
			 */
//			case R.id.read_more_book_detail:
//				cls = BookAboutActivity.class;
//				intent.putExtra("url", UrlUtils.makeWebUrl(Constants.BASE_WEB_URL + "bookinfo?op=showbookinfo&articleid="+pageFactory.getArticleId()));
//				break;
//			case R.id.read_top_mark:
//				if (Constants.BookConfig.SHOP_BOOKS == pageFactory.getBKtype()) {
//					shopMark();
//				} else if (Constants.BookConfig.LOCAL_BOOKS == pageFactory.getBKtype()) {
//					localMark();
//				}
//				break;
			case R.id.null_view:
				initAnimationOut();
				break;
			/**
			 * 跳转书籍目录
			 */
			case R.id.read_catalog:

//				Intent cataIntent = new Intent(mContext, ReadCatalogActivity.class);
//				cataIntent.putExtra("articleid", pageFactory.getArticleId());
//				cataIntent.putExtra("chapterOrder", pageFactory.getChpInfo() == null ? "1" : String.valueOf(pageFactory.getChpInfo().getChapterOrder()));

//				if(null != mContext && mContext instanceof Activity){
//					activity = (Activity) mContext;
//				}
//				activity.startActivityForResult(cataIntent, Constants.REQUEST_CODE.BOOKMARKS);
//				activity.overridePendingTransition(R.anim.dialog_from_left_in, R.anim.dialog_from_left_out);
				dismiss();
				EPupReadActivity ePupActivity = (EPupReadActivity) this.mContext;
				ePupActivity.mViewPager.setCurrentItem(0);
				ePupActivity.mDrawerLayout.openDrawer(GravityCompat.START);
				break;
			/**
			 * 设置
			 */
			case R.id.read_setting:

				BookReadMoreSettingDialog.getInstance(this.mContext).showView();
				break;
			/**
			 * 日间夜间切换
			 */
            case R.id.read_dayOrNight:
                if(readSetting.getReadStyle() == ThemeManager.READ_STYLE_THEME_DEFAULT){

                    readSetting.setReadStyle(ThemeManager.READ_STYLE_THEME_NIGHT);
					EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.READ_STYLE_THEME,ThemeManager.READ_STYLE_THEME_NIGHT));
                }else{

                    readSetting.setReadStyle(ThemeManager.READ_STYLE_THEME_DEFAULT);
					EventBus.getDefault().post(new MessageEvent(Constants.ReadStatus.READ_STYLE_THEME,ThemeManager.READ_STYLE_THEME_DEFAULT));
                }
                popNightOrDay();
                break;
            case R.id.read_more:

            	ToastUtils.showToast("read_more");
                break;
		}

		if(null != cls){
			intent.setClass(mContext, cls);
			mContext.startActivity(intent);
		}
		initAnimationOut();
	}

	/**
	 * 日间夜间模式切换
	 */
	private void popNightOrDay() {

		Drawable drawable;
		if(readSetting.getReadStyle() == ThemeManager.READ_STYLE_THEME_DEFAULT){

			dayOrNight.setText(getResources().getString(R.string.read_day));
			drawable= getResources().getDrawable(R.mipmap.read_setting_day_mode_ic);
		}else {

			dayOrNight.setText(getResources().getString(R.string.read_night));
			drawable= getResources().getDrawable(R.mipmap.read_setting_night_mode_ic);
		}
		// 这一步必须要做,否则不会显示.
		drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
		dayOrNight.setCompoundDrawables(null,drawable,null,null);
	}

	/**
	 * 书签处理
	 */
	private void shopMark() {

//		Chapter bkChipInfo = pageFactory.getChpInfo();
//		if (null == bkChipInfo) {
//			return;
//		}
		if (isMarkPage) {
//
//			BookMarkEntity bookMarkEntity = new BookMarkEntity(0);
//			bookMarkEntity.setArticleId(Integer.parseInt(pageFactory.getArticleId()));
//			bookMarkEntity.setChapterId(bkChipInfo.getChapterId());
//			bookMarkEntity.setBegin(pageFactory.getCurPage());
//			bookMarkEntity.setWord(pageFactory.getFirstLineText());
//			bookMarkEntity.setChapterOrder(bkChipInfo.getChapterOrder());
//			bookMarkEntity.setIsFree(bkChipInfo.getJsFree());
//			bookMarkEntity.setChapterName(bkChipInfo.getChapterName());
//
//			DatabaseManager.getInstance().deleteBookMaker(bookMarkEntity);
//			bookMark.setSelected(true);
//			isMarkPage = false;
//			ToastUtils.showToast(R.string.delete_bookstore_success);
//		} else {
//
//			BookMarkEntity bookMarkEntity = new BookMarkEntity(0);
//			bookMarkEntity.setArticleId(Integer.parseInt(pageFactory.getArticleId()));
//			bookMarkEntity.setChapterId(bkChipInfo.getChapterId());
//			bookMarkEntity.setBegin(pageFactory.getCurPage());
//			bookMarkEntity.setWord(pageFactory.getFirstLineText());
//			bookMarkEntity.setChapterOrder(bkChipInfo.getChapterOrder());
//			bookMarkEntity.setIsFree(bkChipInfo.getJsFree());
//			bookMarkEntity.setChapterName(bkChipInfo.getChapterName());
//			bookMarkEntity.setTime(System.currentTimeMillis());
//			bookMarkEntity.setOwner(UserSP.getInstance().getUserName());
//
//			DatabaseManager.getInstance().addMaker(bookMarkEntity);
//			bookMark.setSelected(false);
//			isMarkPage = true;
//			ToastUtils.showToast(R.string.add_bkstore_success);
		}
	}

	/**
	 * 本地书签处理
	 */
	private void localMark() {

//		Chapter bkChipInfo = pageFactory.getChpInfo();
//		if (null == bkChipInfo) {
//			return;
//		}
//
//		if (isMarkPage) {
//
//			BookMarkEntity bookMarkEntity = new BookMarkEntity(0);
//			bookMarkEntity.setArticleId(Integer.parseInt(pageFactory.getArticleId()));
//			bookMarkEntity.setChapterId(bkChipInfo.getChapterId());
//			bookMarkEntity.setBegin(pageFactory.getCurPage());
//			bookMarkEntity.setWord(pageFactory.getFirstLineText());
//			bookMarkEntity.setChapterOrder(bkChipInfo.getChapterOrder());
//			bookMarkEntity.setIsFree(bkChipInfo.getJsFree());
//			bookMarkEntity.setChapterName(bkChipInfo.getChapterName());
//
//			DatabaseManager.getInstance().deleteBookMaker(bookMarkEntity);
//			bookMark.setSelected(true);
//			isMarkPage = false;
//			ToastUtils.showToast(R.string.delete_bookstore_success);
//		} else {
//
//			BookMarkEntity bookMarkEntity = new BookMarkEntity(0);
//			bookMarkEntity.setArticleId(Integer.parseInt(pageFactory.getArticleId()));
//			bookMarkEntity.setChapterId(bkChipInfo.getChapterId());
//			bookMarkEntity.setBegin(pageFactory.getCurPage());
//			bookMarkEntity.setWord(pageFactory.getFirstLineText());
//			bookMarkEntity.setChapterOrder(bkChipInfo.getChapterOrder());
//			bookMarkEntity.setIsFree(bkChipInfo.getJsFree());
//			bookMarkEntity.setChapterName(bkChipInfo.getChapterName());
//			bookMarkEntity.setTime(System.currentTimeMillis());
//			bookMarkEntity.setOwner(UserSP.getInstance().getUserName());
//
//			DatabaseManager.getInstance().addMaker(bookMarkEntity);
//
//			bookMark.setSelected(false);
//			isMarkPage = true;
//			ToastUtils.showToast(R.string.add_bkstore_success);
//		}
	}

//	拖动条进度改变的时候调用
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {

		progress = seekBar.getProgress();
//		progressText.setText(progress + "%");
		EventBus.getDefault().post(new MessageEvent(Constants.ReadDialogSetting.READ_PROGRESS,progress));
	}

//	拖动条开始拖动的时候调用
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {

	}

//	拖动条停止拖动的时候调用
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {

	}
}
